package com.colin.library.help;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.colin.library.help.permission.PermissionHelp;

import java.io.File;
import java.util.Arrays;

/**
 * Created by Administrator on 2017/11/22.
 * 图片工具类 选择图片
 */

public class ImageUtil {

    public final static int REQUEST_PERMISSION_CAMERA = 10001;
    public final static int REQUEST_PERMISSION_ALBUM = 10002;
    public final static int REQUEST_RESULT_CAMERA = 10001;
    public final static int REQUEST_RESULT_ALBUM = 10002;
    public final static int REQUEST_RESULT_CROP = 10003;

    /**
     * 选择图片接口回调
     */
    public interface OnChooseImage {
        void image(boolean success, File file, Object object);
    }


    //    选取手机图片全局变量
    private OnChooseImage mOnChooseImage;
    private Activity mActivity;
    private Fragment mFragment;
    private File mImageFile;            //相机剪切需要创建File
    private Uri mUri;                   //相机得到的uri
    private boolean isCrop = false;     //是否需要剪切 默认不需要剪切
    private boolean isSquare = true;    //是否正方形图片 默认是

    public static class Holder {
        static ImageUtil instance = new ImageUtil();
    }

    private ImageUtil() {
    }

    public static ImageUtil getInstance() {
        return Holder.instance;
    }

    /**
     * 弹框显示提醒用户选择方式
     * 用户必须实现 onRequestPermissionsResult onActivityResult 两个方法
     *
     * @param activity
     * @param onChooseImage
     */
    public void showDialog(final Activity activity, final OnChooseImage onChooseImage) {
        this.showDialog(activity, isCrop, isSquare, onChooseImage);
    }

    public void showDialog(final Activity activity, final boolean isCrop, final OnChooseImage onChooseImage) {
        this.showDialog(activity, isCrop, isSquare, onChooseImage);
    }

    public void showDialog(final Activity activity, final boolean isCrop, final boolean isSquare, final OnChooseImage onChooseImage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, android.support.design.R.style.Theme_Design_BottomSheetDialog);
        builder.setItems(new String[]{"相机", "相册", "取消"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //没有接口回调 拿到值也无用
                if (null == onChooseImage) {
                    return;
                }
                //取消
                if (which == 2) {
                    onChooseImage.image(false, null, "操作取消");
                    return;
                }
                //相机
                if (which == 0) {
                    openCamera(activity, isCrop, isSquare, onChooseImage);
                }
                //相册
                if (which == 1) {
                    openAlbum(activity, isCrop, isSquare, onChooseImage);
                }
            }
        });
        final AlertDialog dialog = builder.create();
        dialog.show();
    }

    public void showDialog(final Fragment fragment, final OnChooseImage onChooseImage) {
        this.showDialog(fragment, isCrop, onChooseImage);
    }

    public void showDialog(final Fragment fragment, final boolean isCrop, final OnChooseImage onChooseImage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getActivity(), android.support.design.R.style.Theme_Design_BottomSheetDialog);
        builder.setItems(new String[]{"相机", "相册", "取消"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (which == 2 && null != onChooseImage) {
                    onChooseImage.image(false, null, "操作取消");
                    return;
                }
                if (which == 2) {
                    return;
                }
                if (which == 0) {
                    openCamera(fragment, isCrop, onChooseImage);
                }
                if (which == 1) {
                    openAlbum(fragment, isCrop, onChooseImage);
                }
            }
        });
        final AlertDialog dialog = builder.create();
        dialog.show();
    }

    public void showDialog(final Fragment fragment, final boolean isCrop, final boolean isSquare, final OnChooseImage onChooseImage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getActivity(), android.support.design.R.style.Theme_Design_BottomSheetDialog);
        builder.setItems(new String[]{"相机", "相册", "取消"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //没有接口回调 拿到值也无用
                if (null == onChooseImage) {
                    return;
                }
                //取消
                if (which == 2) {
                    onChooseImage.image(false, null, "操作取消");
                    return;
                }
                //相机
                if (which == 0) {
                    openCamera(fragment, isCrop, isSquare, onChooseImage);
                }
                //相册
                if (which == 1) {
                    openAlbum(fragment, isCrop, isSquare, onChooseImage);
                }
            }
        });
        final AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 调用系统相机实现拍照
     * 其中 MediaStore.EXTRA_OUTPUT 数据表示，拍照所得图片保存到指定目录下的文件（一般会在 SD 卡中创建当前应用的目录，并创建临时文件保存图片）。
     * 然后，在 onActivityResult 方法中根据文件路径获取图片。
     * 如果不为 intent 添加该数据的话，将在 onActivityResult 的 intent 对象中返回一个 Bitmap 对象，通过如下代码获取：
     * Bitmap bmp = data.getParcelableExtra("data");这里的 Bitmap 对象是拍照所得图片的一个缩略图
     * <p>
     * 所以，调用系统相机时，一般都会添加 MediaStore.EXTRA_OUTPUT 参数
     * <p>
     * 拍照图片旋转问题
     */
    public void openCamera(Activity activity, OnChooseImage onChooseImage) {
        this.openCamera(activity, isCrop, isSquare, onChooseImage);
    }

    public void openCamera(Activity activity, boolean isCrop, OnChooseImage onChooseImage) {
        this.openCamera(activity, isCrop, isSquare, onChooseImage);
    }

    public void openCamera(Activity activity, boolean isCrop, boolean isSquare, OnChooseImage onChooseImage) {
        clearData();
        this.mActivity = activity;
        this.mOnChooseImage = onChooseImage;
        this.isCrop = isCrop;
        this.isSquare = isSquare;
        if (!PermissionHelp.getInstance().checkPermission(activity, Arrays.asList(PermissionHelp.PERMISSIONS_CAMERA), REQUEST_PERMISSION_CAMERA)) {
            return;
        }
        //适配7.0
        if (Build.VERSION.SDK_INT >= 24) {
            mUri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", getImageFile());
        } else {
            mUri = Uri.fromFile(getImageFile());
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        activity.startActivityForResult(intent, REQUEST_RESULT_CAMERA);
    }

    public void openCamera(Fragment fragment, OnChooseImage onChooseImage) {
        this.openCamera(fragment, isCrop, isSquare, onChooseImage);
    }

    public void openCamera(Fragment fragment, boolean isCrop, OnChooseImage onChooseImage) {
        this.openCamera(fragment, isCrop, isSquare, onChooseImage);
    }

    public void openCamera(Fragment fragment, boolean isCrop, boolean isSquare, OnChooseImage onChooseImage) {
        clearData();
        this.mActivity = fragment.getActivity();
        this.mFragment = fragment;
        this.mOnChooseImage = onChooseImage;
        this.isCrop = isCrop;
        this.isSquare = isSquare;
        if (!PermissionHelp.getInstance().checkPermission(fragment, Arrays.asList(PermissionHelp.PERMISSIONS_CAMERA), REQUEST_PERMISSION_CAMERA)) {
            return;
        }
        //适配7.0
        if (Build.VERSION.SDK_INT >= 24) {
            mUri = FileProvider.getUriForFile(fragment.getActivity(), mActivity.getPackageName() + ".fileprovider", getImageFile());
        } else {
            mUri = Uri.fromFile(getImageFile());
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        fragment.startActivityForResult(intent, REQUEST_RESULT_CAMERA);
    }

    public void openAlbum(Activity activity, OnChooseImage onChooseImage) {
        this.openAlbum(activity, isCrop, isSquare, onChooseImage);
    }

    public void openAlbum(Activity activity, boolean isCrop, OnChooseImage onChooseImage) {
        this.openAlbum(activity, isCrop, isSquare, onChooseImage);
    }

    public void openAlbum(Activity activity, boolean isCrop, boolean isSquare, OnChooseImage onChooseImage) {
        clearData();
        this.mActivity = activity;
        this.mOnChooseImage = onChooseImage;
        this.isCrop = isCrop;
        this.isSquare = isSquare;
        if (!PermissionHelp.getInstance().checkPermission(activity, Arrays.asList(PermissionHelp.PERMISSIONS_STORAGE), REQUEST_PERMISSION_ALBUM)) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片类型
        activity.startActivityForResult(intent, REQUEST_RESULT_ALBUM);
    }

    public void openAlbum(Fragment fragment, OnChooseImage onChooseImage) {
        this.openAlbum(fragment, isCrop, isSquare, onChooseImage);
    }

    public void openAlbum(Fragment fragment, boolean isCrop, OnChooseImage onChooseImage) {
        this.openAlbum(fragment, isCrop, isSquare, onChooseImage);
    }

    public void openAlbum(Fragment fragment, boolean isCrop, boolean isSquare, OnChooseImage onChooseImage) {
        clearData();
        this.mActivity = fragment.getActivity();
        this.mFragment = fragment;
        this.mOnChooseImage = onChooseImage;
        this.isCrop = isCrop;
        this.isSquare = isSquare;
        if (!PermissionHelp.getInstance().checkPermission(fragment, Arrays.asList(PermissionHelp.PERMISSIONS_STORAGE), REQUEST_PERMISSION_ALBUM)) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片类型
        fragment.startActivityForResult(intent, REQUEST_RESULT_ALBUM);
    }

    /**
     * 剪切图片
     *
     * @param uri
     */
    private void cropImage(Uri uri) {
        if (null == mOnChooseImage) {
            return;
        }
        if (null == uri) {
            mOnChooseImage.image(false, null, "获取获取失败");
        }

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //设置 return-data 参数为 true 时，返回的 Bitmap 对象也为缩略图，获取方式与前面所述相机拍照获取 Bitmap 的方式一致；
        intent.putExtra("crop", "true");
        //outputX 与 outputY 值设置太大时，容易出现卡屏现象；
        intent.putExtra("aspectX", isSquare ? 3 : 4);
        intent.putExtra("aspectY", 3);
        //调用系统相册并裁剪时，如果使用MediaStore.EXTRA_OUTPUT参数，Uri 尽量不要设置为源文件对应的 Uri 值，另做保存，不损坏系统相册中的源图文件；
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getImageFile()));
        if (null != mFragment) {
            mFragment.startActivityForResult(intent, REQUEST_RESULT_CROP);
        } else {
            mActivity.startActivityForResult(intent, REQUEST_RESULT_CROP);
        }
    }

    /**
     * 实现界面 必须实现此方法  fragment 调用 父界面Activity 必须实现super方法
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (PermissionHelp.getInstance().onRequestPermissionsResult(REQUEST_PERMISSION_CAMERA, grantResults)) {
            if (null != mFragment) {
                openCamera(mFragment, mOnChooseImage);
            } else {
                openCamera(mActivity, mOnChooseImage);
            }
        }
        if (PermissionHelp.getInstance().onRequestPermissionsResult(REQUEST_PERMISSION_ALBUM, grantResults)) {
            if (null != mFragment) {
                openAlbum(mFragment, mOnChooseImage);
            } else {
                openAlbum(mActivity, mOnChooseImage);
            }
        }
    }

    /**
     * 实现界面 必须实现此方法  fragment 调用 父界面Activity 必须实现super方法
     *
     * @param requestCode
     * @param resultCode
     * @param intent
     */
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (null == mOnChooseImage) {
            return;
        }
        if (resultCode != Activity.RESULT_OK) {
            mOnChooseImage.image(false, null, "图片选择取消");
            return;
        }
        //需要压缩 方向  保留原件图片
        if (requestCode == REQUEST_RESULT_CAMERA) {
            mImageFile = BitmapHelp.getInstance().getRotateImageFromCamera(getImageFile());
        }
        //剪切
        if (requestCode == REQUEST_RESULT_CROP) {
            mOnChooseImage.image(null != getImageFile(), getImageFile(), null != getImageFile() ? "获取图片成功" : "获取图片失败");
            return;
        }
        //相机剪切
        if (requestCode == REQUEST_RESULT_CAMERA && isCrop) {
            cropImage(mUri);
            return;
        }
        //相册剪切
        if (requestCode == REQUEST_RESULT_ALBUM && isCrop) {
            cropImage(intent.getData());
            return;
        }
        //相机
        if (requestCode == REQUEST_RESULT_CAMERA) {
            mOnChooseImage.image(null != getImageFile(), getImageFile(), null != getImageFile() ? "获取图片成功" : "获取图片失败");
            return;
        }
        //相册 需要处理图片 Uri转File
        if (requestCode == REQUEST_RESULT_ALBUM) {
            File file = getAlbumUriToFile(mActivity, intent.getData());
            mOnChooseImage.image(null != file, file, null != file ? "获取图片成功" : "获取图片失败");
            return;
        }
    }



    public void clearData() {
        this.mActivity = null;
        this.mFragment = null;
        this.mOnChooseImage = null;
        this.mImageFile = null;
        this.mUri = null;
        this.isCrop = false;
        this.isSquare = true;
    }

    /**
     * 相册中的 图片 uri转File
     *
     * @param activity
     * @param uri
     * @return the file path or null
     */
    public static File getAlbumUriToFile(final Activity activity, final Uri uri) {
        if (null == uri) {
            return null;
        }
        File file = null;
        String scheme = uri.getScheme();
        if (TextUtils.isEmpty(scheme) || ContentResolver.SCHEME_FILE.equals(scheme)) {
            file = new File(uri.getPath());
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = activity.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor && cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        file = new File(cursor.getString(index));
                        break;
                    }
                }
            }
            if (null != cursor) {
                cursor.close();
            }
        }
        return file;
    }

    /**
     * 拍照 剪切创建文件
     *
     * @return
     */
    public File getImageFile() {
        if (null != mImageFile) {
            return mImageFile;
        }
        mImageFile = getNewImageFile();
        return mImageFile;
    }

    /**
     * 创建图片文件
     *
     * @return
     */
    public File getNewImageFile() {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".jpg");
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        return file;
    }

}
